package com.imooc.mymall.controller;

import com.imooc.mymall.domain.common.ResponseResult;
import com.imooc.mymall.exception.BusinessException;
import com.imooc.mymall.exception.ErrorCodeEnum;
import com.imooc.mymall.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.io.IOException;

/**
 * <h1>文件服务Controller</h1>
 * @Author: crowsjian
 * @Date: 2020/7/16 21:40
 */
@RestController
@RequestMapping("/api/files")
@Slf4j
public class FileController {

    @Resource(name = "fileServiceImpl")
    private FileService fileService;

    /**
     * <h2>文件上传</h2>
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public ResponseResult<String> upload(@NotNull MultipartFile file){
        // 文件上传..
        try {
            fileService.upload(file.getInputStream(),file.getOriginalFilename());
        } catch (Exception e) {
            log.error("文件上传失败",e);
            throw new BusinessException(ErrorCodeEnum.FILE_UPLOAD_ERROR,e);
        }
        return ResponseResult.success(file.getOriginalFilename());
    }
}
